<template>
  <div class="ipad-container">
    <the-navigation>
    </the-navigation>
    <el-button type="warning" class="control-btn warning" @click="showTestInjector">
      <el-icon><data-analysis /></el-icon>
      <span>测试</span>
    </el-button>

    <main class="main-content">
      <div class="data-cards">
        <div class="data-card time-card">
          <div class="card-content">
            <div class="card-left">
              <div class="card-icon">
                <el-icon>
                  <timer />
                </el-icon>
              </div>
              <div class="card-label">用时</div>
            </div>
            <div class="card-right">
              <!-- 第一个卡片没有修改按钮，保持右侧空白 -->
            </div>
          </div>
          <div class="card-value">
            {{ formatTime(currentTime) }}
            <span class="unit">秒</span>
          </div>
        </div>

        <div class="data-card pile-card">
          <div class="card-content">
            <div class="card-left">
              <div class="card-icon">
                <el-icon>
                  <warning />
                </el-icon>
              </div>
              <div class="card-label">踢漏桩数</div>
            </div>
            <div class="card-right">
              <el-button class="edit-button" text @click="editPenalty">修改</el-button>
            </div>
          </div>
          <div class="card-value">
            {{ missedCones + kickedCones }}
            <span class="unit">个</span>
            <!-- 调试信息 -->
            <div style="font-size: 12px; color: #999; margin-top: 5px;">
              漏桩: {{ missedCones }}, 踢桩: {{ kickedCones }}
            </div>
          </div>
        </div>

        <div class="data-card land-card">
          <div class="card-content">
            <div class="card-left">
              <div class="card-icon">
                <el-icon>
                  <position />
                </el-icon>
              </div>
              <div class="card-label">浮脚落地</div>
            </div>
            <div class="card-right">
              <el-button class="edit-button" text @click="toggleGroundTouch">修改</el-button>
            </div>
          </div>
          <div class="card-value">
            {{ groundTouch ? '是' : '否' }}
          </div>
        </div>
      </div>
      <!-- 最终成绩 -->
      <div class="final-result-text">
        <div class="result-section">
          <h3>最终成绩</h3>
          <div class="status-badge" :class="{ 'valid': isValidResult, 'invalid': !isValidResult }">
            {{ isValidResult ? '有效' : '无效' }}
          </div>
          <div class="score-layout">
            <div class="final-score-center">
              <div class="final-score-value">{{ formatTime(finalScore) }}</div>
              <!-- 控制按钮组 -->
              <div class="control-panel">
                <el-button type="success" class="control-btn success" @click="handleStartClick">
                  <el-icon><video-play /></el-icon>
                  <span>开始</span>
                </el-button>
                <el-button type="danger" class="control-btn danger" @click="handleStopClick">
                  <el-icon><video-pause /></el-icon>
                  <span>结束</span>
                </el-button>
                <el-button type="primary" class="control-btn primary" @click="handleResetClick">
                  <el-icon>
                    <refresh />
                  </el-icon>
                  <span>重置</span>
                </el-button>
              </div>
            </div>
            <div class="score-details">
              <div class="score-detail-item">
                <span class="detail-label">实际时长：</span>
                <span class="detail-value highlight">{{ formatTime(currentTime) }}</span>
              </div>
              <div class="score-detail-item" v-if="missedCones > 0">
                <span class="detail-label">漏桩</span>
                <span class="detail-value highlight">{{ missedCones }}</span>
                <span class="detail-label">（罚时</span>
                <span class="detail-value highlight">{{ missedConesPenalty.toFixed(1) }}</span>
                <span class="detail-label">秒）</span>
              </div>
              <div class="score-detail-item" v-if="kickedCones > 0">
                <span class="detail-label">踢桩</span>
                <span class="detail-value highlight">{{ kickedCones }}</span>
                <span class="detail-label">（罚时</span>
                <span class="detail-value highlight">{{ kickedConesPenalty.toFixed(1) }}</span>
                <span class="detail-label">秒）</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 桩桶可视化组件 -->
      <cone-visualizer ref="conesVisualizer" @status-change="handleConeStatusChange" />

      <!-- 偏移曲线可视化组件 -->
      <div class="offset-curve-section">
        <h3>偏移曲线分析</h3>
        <offset-curve-visualizer :width="800" :height="200" :offset-data="offsetData" />
      </div>



      <!-- 成绩记录 -->
      <div class="records-section">
        <div class="records-title">成绩记录</div>
        <div class="records-actions">
          <el-button class="simple-button" @click="exportRecords">
            <el-icon>
              <download />
            </el-icon>
            导出成绩记录
          </el-button>
          <el-button class="simple-button danger" :disabled="!selectedRecords.length" @click="batchDeleteRecords">
            <el-icon>
              <delete />
            </el-icon>
            删除所选 ({{ selectedRecords.length }})
          </el-button>
        </div>

        <el-table :data="records" stripe style="width: 100%" class="records-table"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="timestamp" label="时间" min-width="160" />
          <el-table-column prop="time" label="原始用时" min-width="100">
            <template #default="scope">
              <span class="time-value">{{ formatTime(scope.row.time) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="penaltyCount" label="漏桩踢桩数" min-width="90" />
          <el-table-column prop="penaltyTime" label="罚时" min-width="90">
            <template #default="scope">
              <span class="penalty-value">+{{ scope.row.penaltyTime.toFixed(1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="finalScore" label="最终成绩" min-width="110">
            <template #default="scope">
              <span class="final-score" :class="{ 'invalid': !scope.row.valid }">
                {{ scope.row.valid ? formatTime(scope.row.finalScore) : '无效' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="valid" label="状态" min-width="80">
            <template #default="scope">
              <span class="status" :class="{ 'invalid': !scope.row.valid }">
                {{ scope.row.valid ? '有效' : '无效' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="80">
            <template #default="scope">
              <el-button class="delete-btn" text type="danger" @click="deleteRecord(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>

    <!-- 漏桩踢桩修改对话框 -->
    <el-dialog v-model="penaltyDialogVisible" title="修改漏桩踢桩数量" width="300px">
      <el-form>
        <el-form-item label="数量">
          <el-input-number v-model="editingPenaltyCount" :min="0" :max="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="penaltyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPenaltyEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 测试数据注入器 -->
    <test-data-injector ref="testInjectorRef" />
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, onMounted, watch, onActivated, onDeactivated, provide } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TheNavigation from '@/components/TheNavigation.vue'
import ConeVisualizer from '@/components/ConeVisualizer.vue'
import OffsetCurveVisualizer from '@/components/OffsetCurveVisualizer.vue'
import TestDataInjector from '@/components/TestDataInjector.vue'
import mqtt from 'mqtt'
import * as XLSX from 'xlsx'

// MQTT连接相关
const mqttStatus = ref('disconnected')
const mqttClient = ref(null)
const connectedDevices = ref(['DEVICE001']) // 默认设备
const activeDeviceId = ref('DEVICE001')

// 定时器引用
let timerInterval = null

// 比赛状态
const isTimerRunning = ref(false)
const currentTime = ref(0)
const startTime = ref(0)
const penaltyCount = ref(0) // 初始状态改为0
const groundTouch = ref(false)

// 修改对话框
const penaltyDialogVisible = ref(false)
const editingPenaltyCount = ref(0)

// 桩桶可视化组件引用
const conesVisualizer = ref(null)

// 测试数据注入器引用
const testInjectorRef = ref(null)

// 成绩记录 - 改为空数组，从本地存储加载
const records = ref([])

// 添加一个标记变量，表示当前是否有一个进行中的比赛
const hasActiveRace = ref(false)

// 添加一个标记，表示当前是否是新比赛还是修改已有记录
const isNewRace = ref(true)

// 添加一个标记，表示当前记录是否已完成（收到结果消息）
const isRecordCompleted = ref(true)

// 当前活动记录的ID
const activeRecordId = ref(null)

// 选中的记录
const selectedRecords = ref([])

// 偏移数据
const offsetData = ref({})

// 为测试组件提供数据
provide('offsetData', offsetData)
provide('currentTime', currentTime)
provide('penaltyCount', penaltyCount)
provide('groundTouch', groundTouch)
provide('conesVisualizer', conesVisualizer)
provide('records', records)

// 计算罚时（基于实际漏桩和踢桩数量）
const penaltyTime = computed(() => {
  return (missedCones.value + kickedCones.value) * 0.2 // 每个漏桩或踢桩罚时0.2秒
})

// 计算最终成绩
const finalScore = computed(() => {
  return currentTime.value + penaltyTime.value
})

// 分离漏桩和踢桩数量（基于桩桶状态数据）
const missedCones = computed(() => {
  // 直接使用ConeVisualizer组件暴露的计算属性
  if (conesVisualizer.value && conesVisualizer.value.missedCount !== undefined) {
    const missed = conesVisualizer.value.missedCount
    console.log('从ConeVisualizer获取漏桩数量:', missed)
    return missed
  }
  console.log('conesVisualizer不可用或missedCount不存在, conesVisualizer.value:', conesVisualizer.value)
  return 0
})

const kickedCones = computed(() => {
  // 直接使用ConeVisualizer组件暴露的计算属性
  if (conesVisualizer.value && conesVisualizer.value.kickedCount !== undefined) {
    const kicked = conesVisualizer.value.kickedCount
    console.log('从ConeVisualizer获取踢桩数量:', kicked)
    return kicked
  }
  console.log('conesVisualizer不可用或kickedCount不存在, conesVisualizer.value:', conesVisualizer.value)
  return 0
})

// 计算漏桩罚时
const missedConesPenalty = computed(() => {
  return missedCones.value * 0.2
})

// 计算踢桩罚时
const kickedConesPenalty = computed(() => {
  return kickedCones.value * 0.2
})

// 判断成绩是否有效
const isValidResult = computed(() => {
  // 如果浮脚落地或漏桩踢桩总数超过4个，则成绩无效
  return !groundTouch.value && (missedCones.value + kickedCones.value) <= 4
})

//连接MQTT服务器
function connectMqtt() {
  const options = {
    username: 'zxt',
    password: 'zyc123456',
    clean: true,
    connectTimeout: 4000,
    clientId: 'ipad_video_client_' + Math.random().toString(16).substring(2, 8)
  }

  console.log('🔄 正在连接MQTT服务器...')
  console.log(`连接信息: ws://192.168.31.245:8083/mqtt, 客户端ID: ${options.clientId}`)

  mqttClient.value = mqtt.connect('ws://192.168.31.245:8083/mqtt', options)

  // function connectMqtt() {
  //   const options = {
  //     username: 'zxt',
  //     password: '554908',
  //     clean: true,
  //     connectTimeout: 4000,
  //     clientId: 'ipad_video_client_' + Math.random().toString(16).substring(2, 8)
  //   }

  //   console.log('🔄 正在连接MQTT服务器...')
  //   console.log(`连接信息: ws://111.229.27.106:8083/mqtt, 客户端ID: ${options.clientId}`)

  //   mqttClient.value = mqtt.connect('ws://111.229.27.106:8083/mqtt', options)

  mqttClient.value.on('connect', () => {
    console.log('🟢 MQTT服务器连接成功')
    mqttStatus.value = 'connected'

    // 订阅视频录制相关主题
    mqttClient.value.subscribe('roller/cam/MaixCAM/result', { qos: 1 }, (err) => {
      if (!err) {
        console.log('✅ 成功订阅录制结果主题')
      } else {
        console.error('❌ 订阅录制结果主题失败:', err)
      }
    })

    // 订阅与设备连接相关的主题
    console.log('订阅设备发现主题: roller/timer/start')
    mqttClient.value.subscribe('roller/timer/start', (err) => {
      if (!err) {
        console.log('✅ 成功订阅设备发现主题')
      } else {
        console.error('❌ 订阅设备发现主题失败:', err)
      }
    })

    // 确保至少有一个默认设备
    if (connectedDevices.value.length === 0) {
      console.log('添加默认设备DEVICE001到已连接设备列表')
      connectedDevices.value.push('DEVICE001')
    }

    // 延迟一点时间确保MQTT连接稳定后再订阅主题
    setTimeout(() => {
      subscribeToDeviceTopics()

      // 如果可视化组件已经就绪，则设置MQTT客户端
      if (conesVisualizer.value) {
        console.log('桩桶可视化组件已就绪，设置MQTT客户端')
        conesVisualizer.value.setMqttClient(mqttClient.value)
      } else {
        console.log('桩桶可视化组件尚未就绪，将通过watch监听器设置MQTT客户端')
      }
    }, 500)
  })

  mqttClient.value.on('message', (topic, message) => {
    try {
      console.log(`📩 收到MQTT消息: 主题=${topic}`)

      // 如果是视频系统的消息，交给视频播放器组件处理
      if (topic === 'roller/cam/MaixCAM/result') {
        // 这里不需要处理，VideoPlayback 组件会处理
        return
      }

      const data = JSON.parse(message.toString())
      console.log(`消息内容:`, data)

      if (topic === 'roller/timer/start') {
        console.log(`📣 处理设备连接消息: ${JSON.stringify(data)}`)
        handleDeviceConnection(data)
        return
      }

      // 处理特定设备的control主题
      if (topic.includes('/control')) {
        console.log(`🎮 处理控制命令: ${JSON.stringify(data)}`)
        handleTimerControl(data)
        return
      }

      // 处理特定设备的result主题
      if (topic.includes('/result')) {
        console.log(`📊 处理结果数据: ${JSON.stringify(data)}`)

        // 只接收时间字段，单位转换为秒
        if (data.time) {
          const timeValue = (parseFloat(data.time) / 1000).toFixed(3)
          console.log(`转换后的时间: ${timeValue}秒`)

          // 停止计时器
          clearInterval(timerInterval)
          timerInterval = null
          isTimerRunning.value = false

          // 更新当前数据
          currentTime.value = parseFloat(timeValue)

          // 更新当前未完成记录的时间，但不标记为完成
          if (!isRecordCompleted.value && activeRecordId.value) {
            updateRecordTime(parseFloat(timeValue))
          } else {
            console.log('⚠️ 没有未完成的记录，无法更新时间')
            ElMessage.warning('没有进行中的比赛记录')
          }
        }
      }
    } catch (error) {
      console.error('❌ 处理MQTT消息出错:', error)
      ElMessage.error('数据格式错误')
    }
  })

  mqttClient.value.on('error', (err) => {
    console.error('❌ MQTT连接错误:', err)
    mqttStatus.value = 'disconnected'
    ElMessage.error('连接失败')
  })

  mqttClient.value.on('reconnect', () => {
    console.log('🔄 正在尝试重新连接MQTT服务器...')
  })

  mqttClient.value.on('close', () => {
    console.log('🔴 MQTT连接已关闭')
    mqttStatus.value = 'disconnected'
  })
}

// 成绩记录存储键前缀
const STORAGE_KEY_PREFIX = 'roller_records_'

// 保存成绩记录到本地存储
function saveRecordsToStorage() {
  try {
    const userId = '1' // 使用固定用户ID
    const deviceId = activeDeviceId.value
    const storageKey = `${STORAGE_KEY_PREFIX}${userId}_${deviceId}`

    localStorage.setItem(storageKey, JSON.stringify(records.value))
    console.log(`✅ 成功保存 ${records.value.length} 条成绩记录到本地存储`)
  } catch (error) {
    console.error('❌ 保存成绩记录失败:', error)
    ElMessage.error('保存成绩记录失败')
  }
}

// 从本地存储加载成绩记录
function loadRecordsFromStorage() {
  try {
    const userId = '1' // 使用固定用户ID
    const deviceId = activeDeviceId.value
    const storageKey = `${STORAGE_KEY_PREFIX}${userId}_${deviceId}`

    const storedRecords = localStorage.getItem(storageKey)
    if (storedRecords) {
      records.value = JSON.parse(storedRecords)
      console.log(`✅ 从本地存储加载了 ${records.value.length} 条成绩记录`)
    } else {
      console.log('本地存储中没有找到成绩记录')
      records.value = []
    }
  } catch (error) {
    console.error('❌ 加载成绩记录失败:', error)
    ElMessage.error('加载成绩记录失败')
    records.value = []
  }
}

// 保存成绩记录
function saveRecord() {
  // 如果没有有效的用时数据，则不保存记录
  if (currentTime.value <= 0) {
    console.warn('用时数据无效，不保存记录')
    return
  }

  // 如果当前没有进行中的比赛，不应该保存记录
  if (!hasActiveRace.value && isNewRace.value) {
    console.warn('没有进行中的比赛，不保存记录')
    return
  }

  // 格式化当前时间
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const timestamp = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

  // 创建记录
  const record = {
    id: Date.now(), // 使用时间戳作为唯一ID
    timestamp,
    time: currentTime.value,
    penaltyCount: missedCones.value + kickedCones.value, // 使用计算属性
    penaltyTime: penaltyTime.value,
    finalScore: finalScore.value,
    valid: isValidResult.value,
    groundTouch: groundTouch.value
  }

  // 添加到记录列表
  records.value.unshift(record)

  // 保存到本地存储
  saveRecordsToStorage()

  console.log('成绩记录已保存:', record)
  ElMessage.success('成绩已保存')

  // 保存后清除进行中的比赛标记
  hasActiveRace.value = false
  // 如果再次编辑这条记录，则不是新比赛了
  isNewRace.value = false
}

// 删除记录
function deleteRecord(index) {
  ElMessageBox.confirm('确定要删除此记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    records.value.splice(index, 1)
    // 保存更新后的记录到本地存储
    saveRecordsToStorage()
    ElMessage.success('记录已删除')
  }).catch(() => {
    // 取消操作
  })
}

// 导出成绩记录到Excel
function exportRecords() {
  if (records.value.length === 0) {
    ElMessage.warning('没有可导出的成绩记录')
    return
  }

  // 准备导出数据
  const exportData = records.value.map(record => ({
    '时间': record.timestamp,
    '原始用时(秒)': record.time.toFixed(3),
    '漏桩数(个)': record.penaltyCount,
    '罚时(秒)': (record.penaltyCount * 0.2).toFixed(1),
    '最终成绩(秒)': record.valid ? record.finalScore.toFixed(3) : '无效',
    '状态': record.valid ? '有效' : '无效',
    '是否浮脚落地': record.groundTouch ? '是' : '否'
  }))

  // 创建工作簿
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 设置列宽
  const colWidths = [
    { wch: 20 },  // 时间
    { wch: 12 },  // 原始用时
    { wch: 10 },  // 漏桩数
    { wch: 10 },  // 罚时
    { wch: 12 },  // 最终成绩
    { wch: 8 },   // 状态
    { wch: 12 }   // 是否浮脚落地
  ]
  ws['!cols'] = colWidths

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '速度过桩成绩记录')

  // 生成文件名
  const now = new Date()
  const fileName = `速度过桩成绩记录_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}.xlsx`

  // 写入文件并下载
  XLSX.writeFile(wb, fileName)

  ElMessage.success('成绩记录已导出')
}

// 监听设备ID变化，加载对应的记录
watch(activeDeviceId, (newDeviceId) => {
  if (newDeviceId) {
    loadRecordsFromStorage()
  }
})

// 组件挂载时连接MQTT和初始化
onMounted(() => {
  connectMqtt()
  // 加载成绩记录
  loadRecordsFromStorage()

  // 检查是否有未完成的记录
  const incompleteRecord = records.value.find(record => record.completed === false)
  if (incompleteRecord) {
    console.log('发现未完成的记录，正在清理...')
    // 找到未完成的记录并删除
    const index = records.value.indexOf(incompleteRecord)
    if (index !== -1) {
      records.value.splice(index, 1)
      saveRecordsToStorage()
    }
  }

  // 确保初始状态下没有进行中的比赛
  hasActiveRace.value = false
  isRecordCompleted.value = true
  activeRecordId.value = null
})

// 监听mqttClient和conesVisualizer的变化，确保正确设置
watch([() => mqttClient.value, () => conesVisualizer.value], ([newClient, newVisualizer]) => {
  if (newClient && newClient.connected && newVisualizer) {
    console.log('mqttClient和conesVisualizer都已就绪，设置MQTT客户端到可视化组件')
    newVisualizer.setMqttClient(newClient)
  }
}, { immediate: true })

// 处理设备连接
function handleDeviceConnection(data) {
  if (data.ready) {
    console.log(`📱 设备连接成功: ${data.ready}`)

    if (!connectedDevices.value.includes(data.ready)) {
      console.log(`📡 添加新设备到连接列表: ${data.ready}`)
      connectedDevices.value.push(data.ready)
      console.log(`当前已连接设备: ${JSON.stringify(connectedDevices.value)}`)

      // 为新连接的设备订阅主题
      console.log(`准备为设备 ${data.ready} 订阅专属主题...`)
      subscribeToDeviceTopics([data.ready])
    } else {
      console.log(`设备 ${data.ready} 已在连接列表中，无需重复添加`)
    }

    ElMessage.success(`设备 ${data.ready} 连接成功`)
  }
}

// 处理按钮点击和水波效果的通用函数
const addRippleEffect = (event) => {
  const button = event.currentTarget;
  
  // 添加水波效果类
  button.classList.add('ripple');
  
  // 600ms后移除水波效果类，让动画完成
  setTimeout(() => {
    button.classList.remove('ripple');
  }, 600);
}

// 开始按钮点击处理
const handleStartClick = (event) => {
  addRippleEffect(event);
  startTimer();
}

// 结束按钮点击处理
const handleStopClick = (event) => {
  addRippleEffect(event);
  stopTimer();
}

// 重置按钮点击处理
const handleResetClick = (event) => {
  addRippleEffect(event);
  resetSystem();
}

// 开始计时
function startTimer() {
  if (mqttClient.value && mqttStatus.value === 'connected') {
    // 使用当前选中的设备ID构建主题
    const publishTopic = `roller/timer/state`;
    const publishData = { race: 'on' };
    console.log(`📤 发送开始计时指令: 主题=${publishTopic}, 数据=`, publishData);

    mqttClient.value.publish(publishTopic, JSON.stringify(publishData))

    // 不需要立即设置hasActiveRace，等待接收到消息后再设置
    ElMessage.success('计时开始')
  } else {
    ElMessage.warning('MQTT未连接，无法发送指令')
  }
}

// 结束计时
function stopTimer() {
  if (mqttClient.value && mqttStatus.value === 'connected') {
    // 使用当前选中的设备ID构建主题
    const publishTopic = `roller/timer/state`;
    const publishData = { race: 'off' };
    console.log(`📤 发送结束计时指令: 主题=${publishTopic}, 数据=`, publishData);

    mqttClient.value.publish(publishTopic, JSON.stringify(publishData))

    // 不需要立即修改hasActiveRace，等待接收到消息后再修改
    ElMessage.success('计时结束')
  } else {
    ElMessage.warning('MQTT未连接，无法发送指令')
  }
}

// 显示测试数据注入器
function showTestInjector() {
  if (testInjectorRef.value) {
    testInjectorRef.value.showInjector()
  }
}

// 重置系统
function resetSystem() {
  ElMessageBox.confirm('确定要重置系统吗？当前数据将会丢失。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 无论MQTT连接状态如何，都执行本地重置
    console.log('用户确认重置系统')

    // 停止计时器
    if (timerInterval) {
      clearInterval(timerInterval)
      timerInterval = null
      isTimerRunning.value = false
    }

    // 重置计时数据
    currentTime.value = 0

    // 删除未完成的记录
    if (!isRecordCompleted.value && activeRecordId.value) {
      removeIncompleteRecord()
    }

    // 标记没有进行中的比赛
    hasActiveRace.value = false

    // 重置所有状态
    resetAllState()

    // 如果MQTT已连接，发送重置指令
    if (mqttClient.value && mqttStatus.value === 'connected') {
      // 使用当前选中的设备ID构建主题
      const publishTopic = `roller/timer/state`;
      const publishData = { reset: 'on' };
      console.log(`📤 发送重置指令: 主题=${publishTopic}, 数据=`, publishData);

      mqttClient.value.publish(publishTopic, JSON.stringify(publishData))
    } else {
      console.log('MQTT未连接，仅执行本地重置')
    }

    ElMessage.success('系统已重置')
  }).catch(() => {
    // 取消操作
    console.log('用户取消重置系统')
  })
}

// 重置所有状态
function resetAllState() {
  console.log('执行完全重置')

  // 停止计时器
  if (timerInterval) {
    clearInterval(timerInterval)
    timerInterval = null
  }

  // 重置所有状态
  isTimerRunning.value = false
  currentTime.value = 0
  startTime.value = 0
  groundTouch.value = false
  // penaltyCount 现在通过计算属性自动计算，不需要手动重置

  // 重置比赛状态标志
  hasActiveRace.value = false
  isRecordCompleted.value = true
  activeRecordId.value = null

  // 重置桩桶状态
  if (conesVisualizer.value) {
    conesVisualizer.value.resetCones()
  }

  console.log('所有状态已重置')
}

// 更新最新记录
function updateLatestRecord() {
  if (records.value.length > 0 && !isRecordCompleted.value) {
    const latestRecord = records.value[0]

    // 更新记录中的数据
    latestRecord.time = currentTime.value
    latestRecord.penaltyCount = missedCones.value + kickedCones.value // 使用计算属性
    latestRecord.penaltyTime = penaltyTime.value
    latestRecord.finalScore = finalScore.value
    latestRecord.valid = isValidResult.value
    latestRecord.groundTouch = groundTouch.value

    // 记录更新后保存
    saveRecordsToStorage()
    console.log('记录已更新:', latestRecord)
  }
}

// 处理桩桶状态变化 - 桩桶状态已通过计算属性自动处理
function handleConeStatusChange(coneData) {
  console.log(`桩桶状态变更: 漏桩数量=${coneData.missedCount}, 踢桩数量=${coneData.kickedCount}, 未检测数量=${coneData.noReceiveCount}`)

  // 桩桶状态变化会自动触发计算属性更新
  // missedCones 和 kickedCones 会自动从 conesVisualizer 获取最新数据
  console.log(`当前漏桩数量: ${missedCones.value}, 踢桩数量: ${kickedCones.value}`)

  // 如果有未完成的记录，实时更新它
  if (!isRecordCompleted.value && records.value.length > 0) {
    updateLatestRecord()
  }
}

// 切换浮脚落地状态
function toggleGroundTouch() {
  groundTouch.value = !groundTouch.value
  ElMessage.success(`浮脚落地状态已修改为: ${groundTouch.value ? '是' : '否'}`)
}

// 打开漏桩踢桩修改对话框
function editPenalty() {
  editingPenaltyCount.value = penaltyCount.value
  penaltyDialogVisible.value = true
}

// 确认修改漏桩踢桩数量
function confirmPenaltyEdit() {
  // 注意：现在漏桩踢桩数量是基于桩桶状态自动计算的
  // 如果需要修改，应该通过桩桶可视化组件来修改桩桶状态
  ElMessage.warning('漏桩踢桩数量现在基于桩桶状态自动计算，请通过桩桶可视化组件修改桩桶状态')
  penaltyDialogVisible.value = false
}

// 监听成绩数据变化，以便更新记录
watch([currentTime, missedCones, kickedCones, groundTouch], () => {
  // 如果有未完成的记录，实时更新它
  if (!isRecordCompleted.value && records.value.length > 0) {
    updateLatestRecord()
  }
}, { deep: true })

// 格式化时间，保留3位小数
function formatTime(time) {
  return time.toFixed(3)
}

// 组件销毁前清除计时器和MQTT连接
onBeforeUnmount(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }

  // 清除未完成的记录
  if (!isRecordCompleted.value && activeRecordId.value) {
    removeIncompleteRecord()
  }

  if (mqttClient.value) {
    // 取消所有设备订阅
    connectedDevices.value.forEach(deviceId => {
      unsubscribeFromDeviceTopics(deviceId)
    })

    mqttClient.value.end()
  }
})

// 处理MQTT消息中的timer/control
function handleTimerControl(data) {
  console.log('处理计时控制指令:', data)

  if (data.race === 'on') {
    // 在创建新记录前，先完成上一条未完成的记录
    if (!isRecordCompleted.value && activeRecordId.value) {
      console.log('检测到未完成的上一条记录，标记为已完成')
      finalizeLastRecord()
    }

    // 收到开始指令时，标记有一个进行中的比赛
    hasActiveRace.value = true

    // 重置计时器并开始计时
    clearInterval(timerInterval)
    currentTime.value = 0
    startTime.value = Date.now()
    isTimerRunning.value = true

    timerInterval = setInterval(() => {
      currentTime.value = (Date.now() - startTime.value) / 1000
    }, 10)

    // 重置当前成绩数据，但保留桩桶在线状态
    resetCurrentData()

    // 创建新记录
    createNewRecord()

    console.log('比赛开始：计时器已启动，新记录已创建')
    ElMessage.success('比赛开始，计时中...')
  } else if (data.race === 'off') {
    // 收到结束指令时，停止计时器
    clearInterval(timerInterval)
    timerInterval = null
    isTimerRunning.value = false

    // 标记没有进行中的比赛，但记录仍然保持未完成状态
    hasActiveRace.value = false

    console.log('比赛结束：计时器已停止，等待桩桶状态完成更新')
    ElMessage.warning('比赛结束，等待桩桶状态更新')
  } else if (data.reset === 'on') {
    // 收到重置指令时，取消当前进行中的比赛
    hasActiveRace.value = false

    // 如果有未完成的记录，删除它
    if (!isRecordCompleted.value && activeRecordId.value) {
      removeIncompleteRecord()
    }

    // 重置所有状态
    resetAllState()

    console.log('比赛重置：已取消当前比赛，数据已重置')
    ElMessage.warning('比赛已重置，未完成的记录已删除')
  }
}

// 完成上一条记录 - 不再等待结果消息，在下一次比赛开始时完成
function finalizeLastRecord() {
  if (records.value.length > 0 && !isRecordCompleted.value) {
    const latestRecord = records.value[0]

    // 如果当前时间是0，则说明没有收到结果消息，使用计时器时间
    if (latestRecord.time === 0) {
      latestRecord.time = currentTime.value
    }

    // 确保罚时和最终成绩已更新
    latestRecord.penaltyCount = missedCones.value + kickedCones.value // 使用计算属性
    latestRecord.penaltyTime = penaltyTime.value
    latestRecord.finalScore = latestRecord.time + latestRecord.penaltyTime
    latestRecord.valid = isValidResult.value
    latestRecord.groundTouch = groundTouch.value

    // 标记为已完成
    latestRecord.completed = true

    // 保存到本地存储
    saveRecordsToStorage()

    // 更新状态
    isRecordCompleted.value = true
    activeRecordId.value = null

    console.log('上一条记录已完成:', latestRecord)
  }
}

// 重置当前成绩数据，但保留桩桶在线状态
function resetCurrentData() {
  // 清除浮脚落地状态
  groundTouch.value = false

  // 重置桩桶状态（只清除状态，保留在线状态）
  // penaltyCount 现在通过计算属性自动计算，不需要手动重置
  if (conesVisualizer.value) {
    conesVisualizer.value.resetCones()
  }
}

// 取消订阅设备特定的主题
function unsubscribeFromDeviceTopics(deviceId) {
  if (!mqttClient.value || !mqttClient.value.connected) {
    return
  }

  const userId = '1'
  const controlTopic = `roller/timer/${deviceId}/${userId}/control`
  const resultTopic = `roller/timer/${deviceId}/${userId}/result`

  console.log(`📴 取消订阅设备 ${deviceId} 的主题:`)
  console.log(` - 控制主题: ${controlTopic}`)
  console.log(` - 结果主题: ${resultTopic}`)

  mqttClient.value.unsubscribe(controlTopic, (err) => {
    if (err) {
      console.error(`❌ 取消订阅控制主题失败: ${controlTopic}`, err)
    } else {
      console.log(`✅ 已成功取消订阅控制主题: ${controlTopic}`)
    }
  })

  mqttClient.value.unsubscribe(resultTopic, (err) => {
    if (err) {
      console.error(`❌ 取消订阅结果主题失败: ${resultTopic}`, err)
    } else {
      console.log(`✅ 已成功取消订阅结果主题: ${resultTopic}`)
    }
  })

  console.log(`设备 ${deviceId} 的主题已取消订阅`)
}

// 订阅设备特定的主题
function subscribeToDeviceTopics(specificDevices = null) {
  if (!mqttClient.value || !mqttClient.value.connected) {
    console.error('❌ 无法订阅设备主题: MQTT客户端未连接')
    return
  }

  // 强制使用固定用户ID "1"，不从localStorage获取
  const userId = '1'
  const devicesToSubscribe = specificDevices || connectedDevices.value

  console.log('===== 开始订阅设备主题 =====')
  console.log(`当前用户ID: ${userId}`)
  console.log(`需要订阅的设备列表: ${JSON.stringify(devicesToSubscribe)}`)

  if (!devicesToSubscribe || devicesToSubscribe.length === 0) {
    console.warn('⚠️ 没有可用设备需要订阅，请检查connectedDevices是否正确初始化')
    return
  }

  devicesToSubscribe.forEach(deviceId => {
    console.log(`处理设备: ${deviceId}`)

    if (!deviceId) {
      console.warn('⚠️ 设备ID为空，跳过订阅')
      return
    }

    // 订阅设备的控制主题
    const controlTopic = `roller/timer/${deviceId}/${userId}/control`
    // 订阅设备的结果主题
    const resultTopic = `roller/timer/${deviceId}/${userId}/result`

    console.log(`正在订阅设备 ${deviceId} 的主题:`)
    console.log(` - 控制主题: ${controlTopic}`)
    console.log(` - 结果主题: ${resultTopic}`)

    mqttClient.value.subscribe(controlTopic, (err) => {
      if (err) {
        console.error(`❌ 订阅控制主题失败: ${controlTopic}`, err)
      } else {
        console.log(`✅ 成功订阅控制主题: ${controlTopic}`)
      }
    })

    mqttClient.value.subscribe(resultTopic, (err) => {
      if (err) {
        console.error(`❌ 订阅结果主题失败: ${resultTopic}`, err)
      } else {
        console.log(`✅ 成功订阅结果主题: ${resultTopic}`)
      }
    })
  })

  console.log('===== 设备主题订阅完成 =====')
}

// 创建新记录
function createNewRecord() {
  // 格式化当前时间
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const timestamp = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

  // 新记录ID
  const recordId = Date.now()

  // 创建初始记录
  const record = {
    id: recordId,
    timestamp,
    time: 0, // 初始用时为0
    penaltyCount: missedCones.value + kickedCones.value, // 使用计算属性
    penaltyTime: penaltyTime.value,
    finalScore: 0, // 初始最终成绩为0
    valid: isValidResult.value,
    groundTouch: groundTouch.value,
    completed: false // 标记为未完成
  }

  // 添加到记录列表
  records.value.unshift(record)

  // 保存到本地存储
  saveRecordsToStorage()

  // 设置当前活动记录ID
  activeRecordId.value = recordId

  // 标记记录为未完成
  isRecordCompleted.value = false

  console.log('新记录已创建:', record)
}

// 更新记录的时间（在收到结果消息时）
function updateRecordTime(finalTime) {
  if (records.value.length > 0 && !isRecordCompleted.value) {
    const latestRecord = records.value[0]

    // 只更新时间字段，不标记为完成
    latestRecord.time = finalTime
    latestRecord.finalScore = finalTime + latestRecord.penaltyTime

    // 保存到本地存储
    saveRecordsToStorage()

    console.log('记录时间已更新:', latestRecord)
    ElMessage.success('成绩时间已更新')
  }
}

// 删除未完成的记录
function removeIncompleteRecord() {
  if (activeRecordId.value) {
    const index = records.value.findIndex(record => record.id === activeRecordId.value)
    if (index !== -1) {
      records.value.splice(index, 1)
      saveRecordsToStorage()
      console.log('未完成的记录已删除')
    }

    // 重置状态
    activeRecordId.value = null
    isRecordCompleted.value = true
  }
}

// 表格选择变化
function handleSelectionChange(selection) {
  selectedRecords.value = selection
}

// 批量删除记录
function batchDeleteRecords() {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRecords.value.length} 条记录吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 获取所有要删除的记录ID
    const idsToDelete = selectedRecords.value.map(record => record.id)

    // 从数组中过滤掉要删除的记录
    records.value = records.value.filter(record => !idsToDelete.includes(record.id))

    // 重置选中数组
    selectedRecords.value = []

    // 保存到本地存储
    saveRecordsToStorage()

    ElMessage.success(`成功删除 ${idsToDelete.length} 条记录`)
  }).catch(() => {
    // 取消操作
  })
}

// 组件激活时执行（从其他页面返回时）
onActivated(() => {
  console.log('个人赛页面被激活')

  // 检查是否有未完成的记录或有活动比赛
  if (!isRecordCompleted.value || hasActiveRace.value) {
    // 有未完成的记录或比赛进行中，恢复MQTT连接
    if (!mqttClient.value || !mqttClient.value.connected) {
      console.log('恢复MQTT连接')
      connectMqtt()
    }

    // 如果有计时器运行，但时间显示不正确，重新开始计时器
    if (isTimerRunning.value && timerInterval === null) {
      console.log('恢复计时器')
      startTime.value = Date.now() - (currentTime.value * 1000)
      timerInterval = setInterval(() => {
        currentTime.value = (Date.now() - startTime.value) / 1000
      }, 10)
    }

    console.log('保持比赛数据状态')
  } else {
    console.log('没有进行中的比赛，无需保持状态')
    // 无需保持状态，可以执行刷新操作
  }
})

// 组件停用时执行（切换到其他页面时）
onDeactivated(() => {
  console.log('个人赛页面被停用')

  // 如果没有未完成的记录和活动比赛，可以停止计时器节省资源
  if (isRecordCompleted.value && !hasActiveRace.value) {
    // 停止计时器
    if (timerInterval) {
      console.log('停止计时器')
      clearInterval(timerInterval)
      timerInterval = null
    }

    // 不断开MQTT连接，只在组件销毁时断开
    console.log('保持MQTT连接')
  } else {
    // 有未完成的记录或比赛进行中，保持所有状态
    console.log('保持所有状态和连接')
  }
})
</script>

<style scoped>
/* 暗色模式下的卡片透明度变量 */
[data-theme="dark"] {
  --card-bg-opacity: 0.8; /* 暗色模式下卡片背景透明度 */
}

/* iPad容器背景 */
.ipad-container {
  min-height: 100vh;
  overflow: hidden;
}

[data-theme="dark"] .ipad-container {
  background: 
    linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.9)),
    url('/src/assets/花瓣素材_背景系列科技感放射线抽象流数据流背景_194297553.png') no-repeat center center;
  background-size: cover;
}


/* 控制按钮组 */
.control-panel {
  display: flex;
  gap: 45px;
  justify-content: center;
  align-items: center;
}

.control-btn {
  border: none !important;
  position: relative;
  overflow: hidden;
  margin-top: 40px;
  border-radius: 8px !important;
  font-size: 32px !important;
  font-weight: 600 !important;
  height: 60px !important;
  min-width: 180px !important;
  padding: 10px 16px !important;
}

.control-btn.success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%) !important;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.control-btn.danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%) !important;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.control-btn.primary {
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%) !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.control-btn.warning {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c674 100%) !important;
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
}

/* 深色模式下控制按钮去彩色，统一为中性灰 */
[data-theme="dark"] .control-btn,
[data-theme="dark"] .control-btn.success,
[data-theme="dark"] .control-btn.danger,
[data-theme="dark"] .control-btn.primary,
[data-theme="dark"] .control-btn.warning {
  background: linear-gradient(135deg, #03FCFE 0%, #0e9bff 100%) !important;
  box-shadow: 0 4px 12px rgba(6, 132, 160, 0.45) !important;
  border: 1px solid rgba(255, 255, 255, 0.06) !important;
  /* color: #e6e6e6 !important; */
}


[data-theme="dark"] .control-btn :deep(i),
[data-theme="dark"] .control-btn :deep(span) {
  color: #363636 !important;
}

.control-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
  z-index: 0;
}

.control-btn :deep(i),
.control-btn :deep(span) {
  position: relative;
  z-index: 1;
}

/* 水波光晕效果 */
.control-btn {
  position: relative;
  overflow: hidden;
}

.control-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s, opacity 0.6s;
  pointer-events: none;
  z-index: 0;
}

.control-btn.ripple::after {
  width: 300px;
  height: 300px;
  opacity: 0;
}

/* 成功按钮的水波效果 */
.control-btn.success::after {
  background: rgba(103, 194, 58, 0.4);
}

/* 危险按钮的水波效果 */
.control-btn.danger::after {
  background: rgba(245, 108, 108, 0.4);
}

/* 主要按钮的水波效果 */
.control-btn.primary::after {
  background: rgba(64, 158, 255, 0.4);
}

/* 警告按钮的水波效果 */
.control-btn.warning::after {
  background: rgba(230, 162, 60, 0.4);
}

/* 深色模式下的水波效果 */
[data-theme="dark"] .control-btn::after {
  background: rgba(0, 212, 255, 0.3);
}

[data-theme="dark"] .control-btn.success::after,
[data-theme="dark"] .control-btn.danger::after,
[data-theme="dark"] .control-btn.primary::after,
[data-theme="dark"] .control-btn.warning::after {
  background: rgba(0, 212, 255, 0.3);
}

/* 数据卡片区域 */
.data-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 0;
}

  .data-card {
    background: white;
    border-radius: 16px;
    padding: 20px;
    height: 180px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
    transition: all 0.3s;
    position: relative;
    overflow: hidden;
  }

  /* 暗色模式下的卡片透明度 */
  [data-theme="dark"] .data-card {
    background: rgba(255, 255, 255, var(--card-bg-opacity));
    backdrop-filter: blur(10px);
  }

.time-card {
  border-left: 4px solid #409EFF;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
}

.pile-card {
  border-left: 4px solid #e6a23c;
  background: linear-gradient(135deg, #ffffff 0%, #fff9f0 100%);
}

.land-card {
  border-left: 4px solid #f56c6c;
  background: linear-gradient(135deg, #ffffff 0%, #fff0f0 100%);
}

.card-icon {
  font-size: 24px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  width: 42px;
  height: 42px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  flex-shrink: 0;
}

.pile-card .card-icon {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.land-card .card-icon {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.edit-button {
  font-size: 12px;
  color: #409EFF;
  padding: 4px 8px;
  margin: 0;
}

.card-label {
  font-size: 16px;
  color: #c0c0c0;
  font-weight: 500;
  white-space: nowrap;
  margin: 0;
}

.card-value {
  font-size: 36px;
  font-weight: 700;
  color: #32e0ff;
  line-height: 1.2;
}

.unit {
  font-size: 18px;
  color: #e2e2e2;
  font-weight: 400;
  margin-left: 4px;
}

/* 最终成绩 */
  .final-result-text {
    margin-bottom: 0;
    padding: 25px 30px;
    background-color: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
    border-left: 4px solid #409EFF;
    background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
    text-align: center;
  }

  /* 暗色模式下的最终成绩区域透明度 */
  [data-theme="dark"] .final-result-text {
    background: linear-gradient(135deg, rgba(255, 255, 255, var(--card-bg-opacity)) 0%, rgba(240, 247, 255, var(--card-bg-opacity)) 100%);
    backdrop-filter: blur(10px);
  }

.result-section h3 {
  font-size: 48px!important;
  font-weight: 600;
  color: #303133;
  margin-bottom: 0px;
  display: inline-block;
  position: relative;
  padding-left: 15px;
  text-align: left;
}

.result-section h3::before {
  content: '';
  position: absolute;
  left: -2px;
  top: 50%;
  transform: translateY(-43%);
  width: 8px;
  height: 45px;
  background: #0e9bff;
  border-radius: 3px;
}

[data-theme="dark"] .result-section h3::before {
  background: linear-gradient(135deg, var(--neon-blue) 0%, rgba(0, 212, 255, 0.4) 100%);
}

.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 10px;
  color: rgb(255, 255, 255);
}

.status-badge.valid {
  background-color: #2860af;
}

.status-badge.invalid {
  background-color: #f56c6c;
}

/* 成绩布局容器 */
.score-layout {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  gap: 30px;
}

/* 最终成绩居中区域 */
.final-score-center {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.final-score-value {
  font-size: 72px;
  font-weight: 700;
  color: var(--neon-blue);
  text-shadow: 0 0 0px var(--neon-blue);
  margin: 0px 0;
  text-align: center;
  font-family: 'Courier New', monospace;
  position: relative;
}

.final-score-value::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  height: 3px;
  /* background: linear-gradient(90deg, transparent, var(--neon-blue), transparent); */
  /* border-radius: 2px; */
  /* box-shadow: 0 0 10px var(--neon-blue); */
  animation: breathe-underline 6s ease-in-out infinite;
}

@keyframes breathe-underline {
  0% {
    width: 80%;
    opacity: 0.3;
  }
  50% {
    width: 100%;
    opacity: 1;
  }
  100% {
    width: 80%;
    opacity: 0.3;
  }
}

/* 成绩详情样式 */
.score-details {
  position: absolute;
  right: 0;
  top: 20%;
  margin-right: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(84, 207, 255, 0.2);
  min-width: 150px;
}

.score-detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 22px;
  line-height: 1.5;
}

.score-detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #000000;
  font-weight: 400;
  margin-right: 4px;
}

.detail-value.highlight {
  color: var(--neon-blue);
  font-weight: 600;
  font-family: 'LED16Segment', monospace;
  text-shadow: 0 0 8px var(--neon-blue);
  margin: 0 2px;
}

.score-note {
  font-size: 20px;

  text-align: center;
}

[data-theme="dark"] .score-note {
  color: #54cfff;
  font-size: 20px;
}


/* 偏移曲线分析 */
  .offset-curve-section {
    margin-bottom: 24px;
    padding: 25px 30px;
    background-color: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
    border-left: 4px solid #409EFF;
    background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  }

  /* 暗色模式下的偏移曲线分析区域透明度 */
  [data-theme="dark"] .offset-curve-section {
    background: linear-gradient(135deg, rgba(255, 255, 255, var(--card-bg-opacity)) 0%, rgba(240, 247, 255, var(--card-bg-opacity)) 100%);
    backdrop-filter: blur(10px);
  }

.offset-curve-section h3 {
  font-size: 26px;
  font-weight: 600;
  color: #41A0FF;
  margin: 0 0 20px 0;
  text-align: center;
}

/* 成绩记录 */
  .records-section {
    padding: 25px 30px;
    background-color: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
    margin-bottom: 0;
    border-left: 4px solid #409EFF;
    background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  }

  /* 暗色模式下的成绩记录区域透明度 */
  [data-theme="dark"] .records-section {
    background: linear-gradient(135deg, rgba(255, 255, 255, var(--card-bg-opacity)) 0%, rgba(240, 247, 255, var(--card-bg-opacity)) 100%);
    backdrop-filter: blur(10px);
  }

.records-title {
  font-size: 26px;
  font-weight: 600;
  color: #41A0FF;
  margin-bottom: 20px;
  display: inline-block;
  position: relative;
  padding-left: 15px;
}

[data-theme="dark"] .records-title {
  color: #ffffff;
}

.records-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 25px;
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%);
  border-radius: 3px;
}

[data-theme="dark"] .records-title::before {
  background: linear-gradient(135deg, var(--neon-blue) 0%, rgba(0, 212, 255, 0.4) 100%);
}

.records-actions {
  display: flex;
  /* justify-content: flex-start; */
  align-items: flex-start;
  margin-bottom: 15px;
}

.simple-button {
  padding: 8px 16px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.simple-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
}

.simple-button.danger {
  background-color: #f56c6c;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.simple-button.danger:hover {
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.3);
}

.simple-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.records-table {
  margin-top: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.records-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.records-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 500;
  padding: 12px 8px;
  font-size: 14px;
}


.card-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.card-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-right {
  display: flex;
  align-items: center;
}

.card-icon {
  font-size: 24px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  width: 42px;
  height: 42px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  flex-shrink: 0;
}

.card-label {
  font-size: 24px;
  color: #000000;
  font-weight: 500;
  white-space: nowrap;
  margin: 0;
}

[data-theme="dark"] .card-label {
  color: #ffffff;
}

.edit-button {
  font-size: 12px;
  color: #409EFF;
  padding: 4px 8px;
  margin: 0;
}

.card-value {
  margin-top: 20px;
  font-size: 36px;
  font-weight: 700;
  font-family: 'LED16Segment', monospace;
  color: #409EFF;
  line-height: 1.2;
}

.unit {
  font-size: 18px;
  color: #e2e2e2;
  font-weight: 400;
  margin-left: 4px;
}

.time-value {
  font-family: monospace;
  color: #606266;
}

[data-theme="dark"] .time-value {
  color: #54cfff;
}

/* 深色模式下的成绩详情样式 */
[data-theme="dark"] .score-details {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(84, 207, 255, 0.3);
  box-shadow: 0 0 15px rgba(84, 207, 255, 0.1);
}

[data-theme="dark"] .detail-label {
  color: #bebebe;
}

[data-theme="dark"] .detail-value.highlight {
  color: var(--neon-blue);
  text-shadow: 0 0 12px var(--neon-blue);
}

/* 深色模式下的下划线效果 */
[data-theme="dark"] .final-score-value::after {
  background: linear-gradient(90deg, transparent, var(--neon-blue), transparent);
  box-shadow: 0 0 15px var(--neon-blue), 0 0 30px rgba(84, 207, 255, 0.3);
}

.penalty-value {
  color: #e6a23c;
  font-family: monospace;
}

.final-score {
  color: #409EFF;
  font-weight: 600;
  font-family: monospace;
}

.final-score.invalid {
  color: #f56c6c;
}

.status {
  color: #67c23a;
}

.status.invalid {
  color: #f56c6c;
}

.delete-btn {
  padding: 2px 8px;
  color: #f56c6c !important;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .data-cards {
    grid-template-columns: repeat(3, 1fr);
  }

  .data-card {
    height: 140px;
    padding: 15px;
  }

  .card-value {
    font-size: 30px;
  }
}

@media (max-width: 768px) {
  .data-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .data-card {
    height: auto;
    padding: 15px;
  }

  .control-panel {
    flex-wrap: wrap;
    gap: 10px;
  }

  .score-layout {
    flex-direction: column;
    gap: 20px;
  }
  
  .final-score-center {
    order: 1;
  }
  
  .score-details {
    order: 2;
    min-width: auto;
    width: 100%;
  }
  
  .final-score-value {
    font-size: 36px;
  }

  .records-table {
    font-size: 12px;
  }

  .records-section,
  .final-result-text {
    padding: 20px;
  }
}

[data-theme="dark"] .simple-button {
  background: linear-gradient(135deg, #03FCFE 0%, #0e9bff 100%) !important;
  box-shadow: 0 4px 12px rgba(6, 132, 160, 0.45) !important;
  /* border: 1px solid rgba(255, 255, 255, 0.06) !important; */
  color: #002f7b !important;
}

/* 暗色主题 - 偏移曲线分析 */
[data-theme="dark"] .offset-curve-section {
  background: var(--card-bg) !important;
  border-left: 4px solid var(--neon-blue) !important;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3) !important;
}

[data-theme="dark"] .offset-curve-section h3 {
  color: var(--neon-blue) !important;
}

/* 暗色主题 - 表格样式 */
[data-theme="dark"] .records-table {
  background: var(--card-bg) !important;
  border: 1px solid var(--border-color) !important;
}

[data-theme="dark"] .records-table :deep(.el-table__header) {
  background-color: var(--bg-secondary) !important;
}

[data-theme="dark"] .records-table :deep(th) {
  background-color: #2e2e2e!important;
  color: var(--text-primary) !important;
  border-bottom: 1px solid var(--border-color) !important;
}

[data-theme="dark"] .records-table :deep(.el-table__body) {
  background-color: var(--card-bg) !important;
}

[data-theme="dark"] .records-table :deep(td) {
  background-color: var(--card-bg) !important;
  color: var(--text-primary) !important;
  border-bottom: 1px solid var(--border-color) !important;
}

[data-theme="dark"] .records-table :deep(.el-table__row:hover > td) {
  background-color: #00405ce1 !important;
}

/* 覆盖Element Plus的条纹行样式 - 使用最高优先级的选择器 */
[data-theme="dark"] .records-table.el-table :deep(.el-table__row--striped td) {
  background-color: #2e2e2e !important;
}

/* 使用更强的选择器覆盖hover状态 */
[data-theme="dark"] .records-table.el-table.el-table--striped :deep(.el-table__body .el-table__row--striped:hover td) {
  background-color: #00405ce1 !important;
}

[data-theme="dark"] .records-table.el-table.el-table--striped :deep(.el-table__body .el-table__row--striped:hover > td) {
  background-color: #00405ce1 !important;
}

/* 额外的覆盖选择器，确保完全覆盖Element Plus样式 */
[data-theme="dark"] .records-table :deep(.el-table__body .el-table__row--striped td) {
  background-color: #2e2e2e !important;
}

[data-theme="dark"] .records-table :deep(.el-table__body .el-table__row--striped:hover td) {
  background-color: #00405ce1 !important;
}

/* 使用最高优先级的选择器组合 */
[data-theme="dark"] .records-table.el-table.el-table--striped .el-table__body .el-table__row--striped:hover td {
  background-color: #00405ce1 !important;
}

[data-theme="dark"] .records-table.el-table.el-table--striped .el-table__body .el-table__row--striped:hover > td {
  background-color: #00405ce1 !important;
}

[data-theme="dark"] .records-table :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: var(--neon-blue) !important;
  border-color: var(--neon-blue) !important;
}

[data-theme="dark"] .records-table :deep(.el-checkbox__inner) {
  background-color: var(--card-bg) !important;
  border-color: var(--border-color) !important;
}

[data-theme="dark"] .records-table :deep(.el-checkbox__inner:hover) {
  border-color: var(--neon-blue) !important;
}

[data-theme="dark"] .records-table :deep(.el-table__empty-block) {
  background-color: var(--card-bg) !important;
  color: var(--text-secondary) !important;
}
</style>